﻿



create proc Products.SaveAttributes (
	@AttributeID	uniqueidentifier = null output,
	@Name			nvarchar(255),
	@Description	nvarchar(400),
	@Optional		bit,
	@MustHave		bit,
	@ExtraCharge	decimal(11,2),
	@Status		smallint,
	@ErrorMessage	nvarchar(400) output
)
as
begin

	if @AttributeID is null
	begin
		select @AttributeID = NEWID();
	end
	
	if @Name is null
	begin
		set @ErrorMessage = 'Name ist null';
		goto EndWithError;
	end
	if @Description is null
	begin
		set @ErrorMessage = 'Description ist null';
		goto EndWithError;
	end
	if @Optional is null
	begin
		set @ErrorMessage = 'Optional ist null';
		goto EndWithError;
	end
	if @MustHave is null
	begin
		set @ErrorMessage = 'MustHave ist null';
		goto EndWithError;
	end
	if @ExtraCharge is null
	begin
		set @ErrorMessage = 'ExtraCharge ist null';
		goto EndWithError;
	end
	if @Status is null
	begin
		set @ErrorMessage = 'Status ist null';
		goto EndWithError;
	end
	
	begin tran;
	
	with src 
	as
	(
		Select	@AttributeID	'AttributeID',
				@Name			'Name',
				@Description	'Description',
				@Optional		'Optional',
				@MustHave		'MustHave',
				@ExtraCharge	'ExtraCharge',
				@Status		'Status'
	)
	
	merge Products.domAttributes as target
	using src
		on (target.AttributeID = src.AttributeID)
	when matched then
		update set
			Name			= src.Name,
			[Description]	= src.[Description],
			Optional		= src.Optional,
			MustHave		= src.MustHave,
			ExtraCharge		= src.ExtraCharge,
			[Status]		= src.[Status]
			
	when not matched by target then
		insert (
			AttributeID,
			Name,
			[Description],
			Optional,
			MustHave,
			ExtraCharge,
			[Status]
		)
		values (
			src.AttributeID,
			src.Name,
			src.[Description],
			src.Optional,
			src.MustHave,
			src.ExtraCharge,
			src.[Status]
		);
		
	
	commit;
	return 0;
	
EndWithError:
	RAISERROR ( @ErrorMessage, 16, 1);
	return 1;	

end
GO


